package cn.kgc.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.kgc.base.entity.LoginUserInfo;
import cn.kgc.commons.constant.SystemConstant;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

/**
 * <p>解析令牌数据</p>
 */
public class JwtTokenParseUtil {

    /**
     * 解析令牌
     * @param token
     * @return
     * @throws Exception
     */
    public static LoginUserInfo parseToken(String token) throws Exception{
        if(token==null){
            return null;
        }
        Jws<Claims> claimsJws=  getTokenClaims(token); //获得令牌的载体
        //从令牌载体中获得令牌的过期时间
        Date date= claimsJws.getBody().getExpiration();
        Date nowTime=new Date();  //当前的系统时间
        if(date.before(nowTime)){ //令牌的过期时间小于当前的时间,令牌过期
            return null;
        }
        //从令牌中获得用户对应的json格式的字符串
        String userInfoString=
                (String)claimsJws.getBody().get(SystemConstant.JWT_USER_INFO_KEY);
        return JSON.parseObject(userInfoString, LoginUserInfo.class);
    }

    private static Jws<Claims> getTokenClaims(String token)throws Exception{
        return Jwts.parser()
                .setSigningKey(getPublicKey())
                .parseClaimsJws(token);
    }

    private static PublicKey getPublicKey() throws Exception{
        //创建encodeKeySpec对象
        X509EncodedKeySpec encodedKeySpec
                =new X509EncodedKeySpec(Base64Decoder.decode(SystemConstant.PUBLIC_KEY));
        //创建KeyFactory对象
        KeyFactory keyFactory= KeyFactory.getInstance("RSA");
        //获得公钥对象
        return keyFactory.generatePublic(encodedKeySpec);
    }

}
